package com.wetao.lib_common.tupu;


import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.EventBus.EventBusMessage;
import com.wetao.lib_common.EventBus.bean.TpData_command;
import com.wetao.lib_common.R;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.contract.EmptyCon;
import com.wetao.lib_common.presenter.EmptyPre;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.DownloadUtil;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.view.SuperFileView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;


/**
 * 图谱文本阅读页面
 */
@Route(path = ConstantArouter.PATH_COMMON_TUPUPDFACTIVITY)
public class CommonTupuPdfActivity extends BaseActivity<EmptyCon.View, EmptyPre> implements
        EmptyCon.View, View.OnClickListener {


    private static final String TAG = "CommonTupuPdfActivity";
    @Autowired
    int gridId;
    @Autowired
    String fileUrl;
    @Autowired
    String title;

    //文档加载view
    private SuperFileView superFileView;

    @Override
    public int getLayoutId() {
        return R.layout.common_tupu_pdf_activity;
    }

    @Override
    public EmptyPre createPresenter() {
        return new EmptyPre(this);
    }

    @Override
    public EmptyCon.View createView() {
        return this;
    }

    @Override
    public void init() {
        EventBus.getDefault().register(this);
        initView();
        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_DOC_INTO, null));


    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }


    private void initView() {


        initTitleLayout();
        setTvTitle(title, true);
        setFilePath(fileUrl);
        superFileView = findViewById(R.id.mSuperFileView);

        superFileView.setOnGetFilePathListener(new SuperFileView.OnGetFilePathListener() {
            @Override
            public void onGetFilePath(SuperFileView mSuperFileView2) {
                showLoadingDialog();
                getFilePathAndShowFile(mSuperFileView2);
            }

            @Override
            public void onLoadComplete() {
                hideLoadingDialog();
            }

            @Override
            public void onLoadError() {
                hideLoadingDialog();
                ToastUtil.initToast("抱歉，该资源无法打开~");
            }
        });

        superFileView.show();
        iv_back.setOnClickListener(this);
    }


    /**
     * 获取路径并打开
     *
     * @param mSuperFileView2
     */
    private void getFilePathAndShowFile(SuperFileView mSuperFileView2) {

        File cacheFile = FileUtils.getPdfCacheFile(getFilePath());
        if (cacheFile.exists()){
            mSuperFileView2.displayFile(cacheFile);
        }else if (getFilePath().contains("http")){
            downLoadFromNet(getFilePath(), mSuperFileView2);
        }
    }

    private void downLoadFromNet(final String url, final SuperFileView mSuperFileView) {

        //1.网络下载、存储路径、
        File cacheFile = FileUtils.getPdfCacheFile(url);
        if (cacheFile.exists()) {
            if (cacheFile.length() <= 0) {
                LogUtils.d("删除空文件！！");
                cacheFile.delete();
                return;
            }
        }

        File dir = FileUtils.getPDFFolder();

        DownloadUtil.get().download(this, url,dir.getAbsolutePath(), new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(final String path) {
                LogUtils.e("下载txt文件成功");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mSuperFileView.displayFile(new File(path));
                    }
                });
            }

            @Override
            public void onDownloading(final int sum, final int total, final int progress) {

            }

            @Override
            public void onDownloadFailed() {
                LogUtils.e("下载文件失败");
            }

            @Override
            public void onNetwork(boolean isNetwork) {
                LogUtils.e("下载文件成功-网络连接断开");
                File file = FileUtils.getPdfCacheFile(url);
                if (!file.exists()) {
                    LogUtils.d("删除下载失败文件");
                    file.delete();
                }
            }
        });
    }

    public void showLoadingDialog() {
        DialogXUtil.waitDialogShow("正在加载...");
    }

    public void hideLoadingDialog() {
        DialogXUtil.waitDialogDismiss();
    }


    public String getFilePath() {
        return fileUrl;
    }

    public void setFilePath(String filePath) {
        this.fileUrl = filePath;
    }

    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_DOC_OUT, null));
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        if (superFileView != null) {
            superFileView.onStopDisplay();
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busGetMessage(EventBusMessage messageEvent) {
        int action = messageEvent.getAction();
        String msg = messageEvent.getMsg();
        if(action == EventBusMessage.EVENT_BUS_ACTION_DATA_TP) {
            TpData_command cm = JsonUtils.fromJson(msg, TpData_command.class);
            if(cm.getId().intValue() != gridId || !cm.getUrl().equals(fileUrl)) {
                LogUtils.e("切换pfd时：name = " + cm.getName() + ", url = " + cm.getUrl());
                gridId = cm.getId().intValue();
                title = cm.getName();
                fileUrl = cm.getUrl();
                tv_title.setText(cm.getName());

                //setFilePath(fileUrl); //设置新Url地址
                setFilePath(cm.getUrl()); //设置新Url地址
                superFileView.onStopDisplay(); //关闭上一篇
                superFileView.SwitchFileView();
                superFileView.show();
            }
        }
    }

}
